/*****************************************************************************
 * HUSONG PROPRIETARY INFORMATION
 * <p/>
 * The information contained herein is proprietary to HUSONG
 * and shall not be reproduced or disclosed in whole or in part
 * or used for any design or manufacture
 * without direct written authorization from HUSONG.
 * <p/>
 * Copyright (c) 2015 by HUSONG.  All rights reserved.
 *****************************************************************************/
package com.husong.controller.base;

import com.husong.config.Config;
import com.husong.cons.ReturnCodeAndMsg;
import com.husong.pojo.ReturnJsonBean;
import com.husong.service.*;
import com.husong.util.*;
import com.husong.util.sms.BaseSMS;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;

import javax.servlet.http.HttpServletRequest;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author maxmin
 */
public class BaseController {

    @Autowired
    protected TaskExecutor taskExecutor;

    @Autowired
    protected MailUtil mailUtil;

    @Autowired
    protected UserService userService;

    @Autowired
    protected OrderService orderService;

    @Autowired
    protected AdvertService advertService;

    @Autowired
    protected CommentService commentService;

    @Autowired
    protected LikeService likeService;
    
    @Autowired
    protected JPush jPush;

    /**
     * 保存异常信息
     *
     * @param authorName
     * @param modelName
     * @param functionName
     * @param e
     */
    protected void saveException(final String authorName, final String modelName, final String functionName, final Exception e) {
        taskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                e.printStackTrace(new PrintStream(baos));
                String exception = baos.toString();
                // 获得当前的IP地址
                InetAddress addr = null;
                try {
                    addr = InetAddress.getLocalHost();
                } catch (UnknownHostException e1) {
                    e1.printStackTrace();
                }
                String ip = addr.getHostAddress().toString();//获得本机IP

                // 发送错误的邮件
                mailUtil.sendHtmlMail("jincongmin@yihusong.com", "[" + ip + "]" + authorName + ":" + modelName + "==>" + functionName, exception);
            }
        });
    }

    /**
     * 获取客户端ip
     *
     * @param request
     *
     * @return
     */
    protected String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 成功的json
     *
     * @param rb
     */
    protected void returnSuccess(ReturnJsonBean rb) {
        rb.setCode(ReturnCodeAndMsg.SUCCESS);
        rb.setMessage(ReturnCodeAndMsg.SUCCESS_MSG);
    }

    /**
     * 失败的json
     *
     * @param rb
     * @param code
     * @param msg
     */
    protected void returnFail(ReturnJsonBean rb, int code, String msg) {
        rb.setCode(code);
        rb.setMessage(msg);
    }

    /**
     * 发送验证码并缓存
     *
     * @param telephone
     * @param time
     */
    protected void sendCode(String telephone, int time) {
        String code = ValicodeUtil.createCode();
        CacheUtil cache = CacheUtil.getInstance();
        cache.delete(telephone);
        boolean rt = cache.set(telephone, time, code);
        LoggerUtils.info(getClass().getName(), "缓存结果：" + rt);
        BaseSMS.sendLoginValicode(telephone, code);
    }

    /**
     * 登录成功后缓存secret key
     *
     * @param id
     *
     * @return
     */
    protected String cacheLogin(String id) {
        CacheUtil cache = CacheUtil.getInstance();
        String secretKey = UUIDUtil.getUUID();
        cache.set(id, Config.TOKEN_EFFECTIVE_TIME, secretKey);
        return secretKey;
    }
    
    /**
     * 从缓存中获取secretKey
     *
     * @param key
     *
     * @return
     */
    protected String getKey(String key) {
        //从缓存中获取
        CacheUtil cacheUtil = CacheUtil.getInstance();
        Object sk = cacheUtil.get(key);
        if (sk != null) {
            return (String)sk;
        }
        return null;
    }
}
